package sz.szsmk.citizencard.ui.newversion.fragment

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.youzan.androidsdk.account.Token
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_me.*
import kotlinx.android.synthetic.main.layout_body.*
import kotlinx.android.synthetic.main.layout_metop.*
import org.greenrobot.eventbus.EventBus
import sz.szsmk.citizencard.DaggerApplication
import sz.szsmk.citizencard.R
import sz.szsmk.citizencard.model.network.bean.response.*
import sz.szsmk.citizencard.model.network.bean.response.QueryOrderCountRes.OrderCountListBean
import sz.szsmk.citizencard.model.network.bean.response.SeleciUserAuthRes.AuthTypeListBean
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent
import sz.szsmk.citizencard.mvp.BasePresenter
import sz.szsmk.citizencard.ui.adapter.bean.AppHomeCardBean
import sz.szsmk.citizencard.ui.dzsmkfragment.AppBaseFragment
import sz.szsmk.citizencard.ui.newversion.fragment.presenter.MePresenter
import sz.szsmk.citizencard.ui.newversion.fragment.view.MeMvpView
import sz.szsmk.citizencard.util.*
import sz.szsmk.citizencard.widget.GlideCircleTransform
import javax.inject.Inject

class MeFragment : AppBaseFragment(), MeMvpView {

    @Inject
    lateinit var presenter: MePresenter

    private val kefuUrl :String ="https://tyhd.szsmk.com/dingdingkefu/index"

     var phone : String? = null
     var LV : String? = null
     var reaName : String? = null
     var idCard : String? = null

    override fun initPresenters(): Array<BasePresenter<*>>? {
        return arrayOf(presenter)
    }

    override fun getTopTitle() = null

    companion object{
        fun getInstance(): MeFragment? {
            return MeFragment()
        }
    }

    var root:View?=null

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View? {
        if(root==null){
            root = inflater.inflate(R.layout.fragment_me, container, false)
            component.inject(this)
        }
        isViewOK = true
        return root
}



override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    //MainActivity沉浸  手动 空出 状态栏高度
    var layoutParams = rl_content.layoutParams as ViewGroup.MarginLayoutParams
    layoutParams.setMargins(0, ImmersionBar.getStatusBarHeight(context as Activity), 0, 0)
    rl_content.layoutParams = layoutParams
}

private var isViewOK = false //是否完成 View 初始化
    private var isFirst = true //是否为第一次加载

    override fun onResume() {
        super.onResume()
        if (isViewOK && isFirst) {
            //加载数据时判断是否完成view的初始化，以及是不是第一次加载此数据
            //loadDate()
            //加载第一次数据后改变状态，后续不再重复加载
            isFirst = false
        }
        if (isAdded){
            val arguments = arguments
            phone = arguments?.getString("phone")
            LV = arguments?.getString("LV3")
            idCard = arguments?.getString("idCard")
            reaName = arguments?.getString("reaName")
        }

        loadDate()

    }

    fun loadDate() {

        ll_levlStatus.visibility = View.VISIBLE
        rl_assets.visibility = View.GONE
        if(getAccessToken()!=null){
            presenter.getUserInfo()
            presenter.getUserLevel()
            presenter.getUserCredit()
            presenter.getCouponCount()
            presenter.getOrderCount()
            presenter.getNgFinance()
            presenter.getCommonConfig()
        }else{
            loginOut_View()
        }
        //初始化事件
        initEvent()
    }

    //获取用数据
    override fun getUserInfoSuccess(response: IUserInfo?) {
        val json = Gson().toJson(response)
        ACache.get(DaggerApplication.getIns()).put("userinfo", json)

        loginOn_View(response?.userEx!!)
    }

    //获取用户等级
    var appHomeCardBean:AppHomeCardBean?=null
    override fun getUserLevelSuccess(appHomeCardBean: AppHomeCardBean?) {
        //赋值到页面全局
        this.appHomeCardBean = appHomeCardBean

        tv_level.text = appHomeCardBean?.level
        when(appHomeCardBean?.level){
            "L1" -> {
                tv_levelTip.text = "已完成登录注册，升级L2 > "
            }
            "L2" -> {
                tv_levelTip.text = "已完成实名认证，升级L3 > "
            }
            "L3" -> {
                tv_levelTip.text = "已完成L3认证 > "
            }
        }

        val levelDesc: String = appHomeCardBean?.levelDesc!!
        if (levelDesc.contains("银行卡") && levelDesc.contains("人脸识别") && levelDesc.contains("支付宝")) {
            tv_idTip.text = "L3已认证"
        } else {
            if (levelDesc.indexOf("+") > -1) {
                tv_idTip.text = levelDesc.substring(0, levelDesc.length - 1)
            } else {
                tv_idTip.text = levelDesc
            }
        }

        val level: String = appHomeCardBean?.level
        if (level == "L2" || level == "L1") {
            tv_idTip.text = "${level}认证"
        }
        //查询  桂花分
        presenter.getUserAuthInfo()
    }

    //获取积分
    override fun getUserCreditSuccess(response: SignInRes?) {
        //设置 积分和优惠券
        if (response != null) {
            tv_accumulatePoints.text = response.credit.toString()
        } else {
            tv_accumulatePoints.text = "0"
        }
    }
    //获取优惠券
    var couponListBean:CouponListBean?=null
    override fun getCouponCountSuccess(response: CouponListBean) {
        couponListBean = response
        if (response != null) {
            var allCount = 0
            for (i in response.data.indices) {
                allCount += response.data[i].usedCount
            }
            tv_myCoupon.text = allCount.toString()
        } else {
            tv_myCoupon.text = "0"
        }

    }



    //获取认证信息   社保  公积金  桂花分
    override fun getUserAuthInfoSuccess(response: SeleciUserAuthRes?) {
        //社保
        val bean1: AuthTypeListBean = response?.authTypeList?.get(0)!!
        //公积金
        val bean2: AuthTypeListBean = response?.authTypeList?.get(1)!!
        //桂花分
        val bean3: AuthTypeListBean = response?.authTypeList?.get(2)!!
        //L3 未认证     、   未授权   、已授权
        //authType: 1公积金，2社保，3桂花分；isAuth：0未授权，1已授权，2未实名(L3认证)

        when(appHomeCardBean?.level){
            "L3" -> {
                when (bean3.isAuth) {
                    "0" -> {
                        tv_housingFundStatus.text = "未授权"
                        tv_guihuascore.text = "未授权"
                        tv_guihuascore.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_b2ffffff))
                    }
                    "1" -> {
                        tv_housingFundStatus.text = "已授权"
                        tv_guihuascore.text = bean3.ghfScore
                        tv_guihuascore.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_ffffff))
                    }
                }
            }
            else->{
                tv_housingFundStatus.text = "L3未认证"
                tv_guihuascore.text = "L3未认证"
            }
        }

    }

    override fun getNgFinanceSuccess(response: QueryNgFinanceRes?) {
        if (response?.code =="000008") {
            tv_finance.text = "点击查看"
        } else {
            tv_finance.text = response?.assets
        }
    }

    override fun getOrderCountSuccess(response: QueryOrderCountRes) {
        val orderCountList: List<OrderCountListBean> = response.getOrderCountList()
        for (i in orderCountList.indices) {
            val tempBean: OrderCountListBean = orderCountList.get(i)
            when (tempBean.orderType) {
                //1待付款 2已付款 3待写卡 4已完成
                "1" -> if (tempBean.count != 0) {
                    tv_dfk.text = "待付款(" + tempBean.count + ")"
                }
                "3" -> if (tempBean.count != 0) {
                    tv_dxk.text = "待写卡(" + tempBean.count + ")"
                }
            }
        }
    }

    //获取用户 是否显示钱包
    override fun getCommonConfigSuccess(response: MeConfigInfoListRes) {
        if(response?.configInfoList.isNotEmpty()){
            for (bean in response.configInfoList){
                when(bean.id){
                    1 -> {
                        //控制我的钱包是否显示
                        when (bean.tagValue) {
                            "1" -> {
                                rl_wallet.visibility = View.VISIBLE
                                rl_assets.visibility = View.VISIBLE
                            }
                            else -> {
                                rl_wallet.visibility = View.GONE
                            }
                        }
                    }
                    2 -> {
                        //控制个人资产是否显示
                        when (bean.tagValue) {
                            "1" -> {
                                rl_finance.visibility = View.VISIBLE
                                rl_assets.visibility = View.VISIBLE
                            }
                            else -> rl_finance.visibility = View.GONE
                        }
                    }
                    3 -> {
                        //控制 商家服务是否显示
                        when (bean.tagValue) {
                            "1" -> {
                                rl_businessService.visibility = View.VISIBLE
                                rl_assets.visibility = View.VISIBLE
                            }
                            else -> rl_businessService.visibility = View.GONE
                        }
                    }
                }
            }
        }else{
            rl_wallet.visibility = View.GONE
            rl_finance.visibility = View.GONE
            rl_businessService.visibility = View.GONE
            rl_assets.visibility = View.GONE
        }
    }

    override fun accountExist(response: AccountExistRes) {


    }

    override fun onFail(baseBean: BaseBean) {
        when(baseBean.code){
            "000002" -> {
                //token无效
                loginOut_View()
            }
        }
    }

    //登录后 修改view
    private fun loginOn_View(userEx: IUserInfo.UserExBean) {
        Glide.with(activity)
                .load(userEx.photo_url)
                .transform(GlideCircleTransform(context))
                .placeholder(R.mipmap.icon_head_default)
                .into(iv_head)
        tv_nickname.text = userEx.nick_name
        tv_phoneNumber.visibility = View.VISIBLE
        tv_phoneNumber.text = userEx.showMobile

        ll_levlStatus.visibility = View.VISIBLE
    }

    //退出登录修改view
    private fun loginOut_View(){
        Glide.with(activity)
                .load(R.mipmap.icon_head_default)
                .transform(GlideCircleTransform(context))
                .placeholder(R.mipmap.icon_head_default)
                .into(iv_head)
        tv_nickname.text = "未登录，请登录"
        tv_phoneNumber.visibility = View.GONE
        ll_levlStatus.visibility = View.GONE

        tv_accumulatePoints.text = "***"
        tv_guihuascore.text = "***"
        tv_guihuascore.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_ffffff))
        tv_myCoupon.text = "***"

        tv_finance.text = "点击查看"

        tv_dfk.text = "待付款"
        tv_dxk.text = "待写卡"
    }

    private fun initEvent(){
        //点击头像
        iv_head.setOnClickListener {
            JumpUtils.jumptoNatvie(context, "userinfo", 1, Bundle())
        }
        //点击设置
        iv_setting.setOnClickListener {
            JumpUtils.jump(context, "setting", 1)
        }
        //点击姓名
        tv_nickname.setOnClickListener {
            JumpUtils.jumptoNatvie(context, "userinfo", 1, Bundle())
        }
        //点击等级
        ll_levlStatus.setOnClickListener {
            val bundle = Bundle()
            bundle.putSerializable("appHomeCardBean", appHomeCardBean)
            JumpUtils.jumptoNatvie(context, "RealNameActivity", 1, bundle)
        }
        //点击积分
        ll_accumulatePoints.setOnClickListener {
            val message = MessageEvent(MessageEvent.CODE_USERBEHAVIOR)
            message.data = 45
            EventBus.getDefault().post(message)
            //打开积分明细界面
            JumpUtils.jumptoNatvie(context, "SignIn", 1, Bundle())
        }
        //跳转桂花分
        ll_guihuascore.setOnClickListener {
            when(appHomeCardBean?.level){
                "L1", "L2" -> {
                    val bundle = Bundle()
                    bundle.putSerializable("appHomeCardBean", appHomeCardBean)
                    bundle.putString(Constant.TITLE, "桂花分")
                    JumpUtils.jumptoNatvie(context, "RealNameActivity", 1, bundle)
                }
                "L3" -> {
                    val bundle = Bundle()
                    val murl = Constant.SZ_URL + "?" + Constant.EXTENT_GHF
                    bundle.putString("url", murl)
                    bundle.putString(Constant.TITLE, "桂花分")
                    Log.i("桂花分", murl)
                    JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
                }
            }
        }
        //点击优惠券
        ll_mycoupon.setOnClickListener {
            val message = MessageEvent(MessageEvent.CODE_USERBEHAVIOR)
            message.data = 51
            EventBus.getDefault().post(message)

            val bundle = Bundle()
            bundle.putSerializable("couponListBean", couponListBean);
            JumpUtils.jumptoNatvie(context, "myCoupon", 1, bundle)

            //            JumpUtils.jumptoNatvie(context, "CouponListActivity", 1, null)
        }
        //我的钱包
        rl_wallet.setOnClickListener {
            val message = MessageEvent(MessageEvent.CODE_WALLET)
            EventBus.getDefault().post(message)
        }
        //我的资产
        rl_finance.setOnClickListener {
            val message = MessageEvent(MessageEvent.CODE_OPENNG)
            message.data = Constant.NGfinance_me
            EventBus.getDefault().post(message)
        }
        //待付款
        ll_orderdfk.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=2&access_token=" + getAccessToken())
            bundle.putString(Constant.TITLE, "我的订单")
            JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
        }
        //已付款
        ll_orderyfk.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=3&access_token=" + getAccessToken())
            bundle.putString(Constant.TITLE, "我的订单")
            JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
        }
        //代写卡
        ll_orderdxk.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=4&access_token=" + getAccessToken())
            bundle.putString(Constant.TITLE, "我的订单")
            JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
        }
        //已完成
        ll_orderywc.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=5&access_token=" + getAccessToken())
            bundle.putString(Constant.TITLE, "我的订单")
            JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
        }
        //全部订单
        tv_orderAll.setOnClickListener {
            val bundle = Bundle()
            bundle.putString("url", Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=1&access_token=" + getAccessToken())
            bundle.putString(Constant.TITLE, "我的订单" + "  " + Constant.BASE_URL + "app-front-end/#/myOrder/all?page_type=1&access_token=" + getAccessToken())
            JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
        }
        //身份认证
        rl_idlayout.setOnClickListener {
            JumpUtils.jump(context, "RealNameActivity", 1)
        }
        //我的市民卡
        rl_mycitycard.setOnClickListener {
            JumpUtils.jump(context, "cardListActivity", 1)
        }
        //我的电子市民卡
        rl_dzsmk.setOnClickListener {
            val level: String? = appHomeCardBean?.level
            if (level == "L1") {
                JumpUtils.jump(context, "RealNameActivity", 1)
            } else {
                val bundle = Bundle()
                JumpUtils.gotoNeedGesture(context, "elecCitizenCard", bundle)
            }
        }
        //NFC交易记录
        rl_nfcTransaction.setOnClickListener {}
        //我的公积金
        rl_housingFund.setOnClickListener{

            when(appHomeCardBean?.level){
                "L1", "L2" -> {
                    val bundle = Bundle()
                    bundle.putSerializable("appHomeCardBean", appHomeCardBean)
                    JumpUtils.jumptoNatvie(context, "RealNameActivity", 1, bundle)
                }
                "L3" -> {
                    //跳转公积金
                    val bundle = Bundle()
                    val path = Constant.BASE_URL + "app-front-end/#/fund/main?access_token=" + getAccessToken()
                    bundle.putString("url", path)
                    JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
                }
            }
        }
        //商家服务
        rl_businessService.setOnClickListener {
            if(getAccessToken()!=null){
                val userinfo: String? = ACache.get(requireContext()).getAsString("userinfo")
                val mUserInfo = Gson().fromJson(userinfo, IUserInfo::class.java)
                val bundle = Bundle()
                val path = Constant.BASE_URL + "app-front-end/#/wallet/shopService?phone=" + mUserInfo.userEx.mobile
                bundle.putString("url", path)
                JumpUtils.jumptoNatvie(context, "webView", 1, bundle)
            }else{
                JumpUtils.jumptoNatvie(context, "login", 0, null)
            }

        }
        //我的收藏
        rl_collect.setOnClickListener {
            JumpUtils.jump(context, "collection", 1)
        }
        //我的地址管理
        rl_addressList.setOnClickListener {
            JumpUtils.jump(context, "adressadmin", 1)
        }
        //在线客服
        rl_FAQ.setOnClickListener {

            if (Token.getAccessToken() == null) JumpThirdView.baseToJumpView(activity, kefuUrl, "", 0, "")
            else {
                JumpThirdView.baseToJumpView(activity, kefuUrl + "?access_token=" + getAccessToken(), "", 0, "")
            }

        }

    }


    private fun getAccessToken():String?{
        return ACache.get(activity).getAsString("access_token")
    }

}
